<script setup lang="ts">
import { requiredCheck } from "@/utils/verify";
import { ref, onMounted } from "vue";
import { addData, editData } from "@/api/modules/system/account";
import {
  cfg_sn_get,
  cfg_softcheck,
  cfgSoftUpdate,
  cfgSetSyscfg,
  licenseUpload,
  licenseCheck,
  licenseList,
  licenseRequest
} from "@/api/modules/system/params";
import { ElMessage } from "element-plus";

interface Props {
  title?: string;
  rowData?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "新增账号",
  rowData: undefined
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import BaseButton from "@/components/BaseButton/index.vue";
import { downloadTemplate, exportData, importData } from "@/api/modules/resource/host-finger";
import moment from "moment/moment";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    name: [...requiredCheck("请输入用户名")],
    password: [...requiredCheck("请输入密码")],
    passwordRe: [
      {
        validator: (rule, value, callback) => {
          if (value !== updateFormData.password) {
            callback(new Error("两次输入的密码不一致"));
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  },
  defaultData: {
    loginTime: 900
  }
});
const ifaces = ref([]);

async function getIface() {
  try {
    const res = await ifaceAll();
    console.log(res);
    if (res) {
      ifaces.value = Object.values(res);
      console.log(ifaces.value);
    }
    Object.values(res);
  } catch (error) {}
}

const loading = ref(false);

async function submitCb() {
  console.log("files.value", files.value);
  if (!files.value.length) {
    ElMessage.warning("请先上传文件");
    return;
  }
  loading.value = true;
  try {
    await licenseUpload({
      file: files.value[0].raw
    });
    ElMessage.success("授权成功");
    getCfg();
    loading.value = false;
    showHandle.value = false;
  } catch (error) {
    loading.value = false;
  }
}

function addDaysToDate(dateString, days) {
  // 解析日期字符串为 Date 对象
  const date = new Date(dateString.replace(" ", "T")); // 替换空格为 'T' 以适应 ISO 格式

  // 使用 setDate 方法增加天数
  date.setDate(date.getDate() + days);

  // 格式化为 "YYYY-MM-DD HH:mm" 格式
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 获取月份并补零
  const day = String(date.getDate()).padStart(2, "0"); // 获取日期并补零
  const hours = String(date.getHours()).padStart(2, "0"); // 获取小时并补零
  const minutes = String(date.getMinutes()).padStart(2, "0"); // 获取分钟并补零

  // return `${year}-${month}-${day} ${hours}:${minutes}`;
  return `${year}-${month}-${day}`;
}

async function getCfg() {
  const res1 = await licenseList();
  // console.log(res1);
  if (res1.result.data && res1.result.data.length) {
    updateFormData.license = res1.result.data[0][1];
    updateFormData.request = res1.result.data[0][6];
    if (updateFormData.request.length > 0) {
      updateFormData.requestStart = updateFormData.request.split(" ")[0];
    }
    updateFormData.day = res1.result.data[0][4];
    if (updateFormData.requestStart) {
      updateFormData.requestEnd = addDaysToDate(updateFormData.request, Number(updateFormData.day));
    }
    updateFormData.isLicence = true;
  } else {
    updateFormData.isLicence = false;
  }
}

async function setCfg() {
  await cfgSetSyscfg({
    timeout: updateFormData.loginTime,
    syslogo: ""
  });
  ElMessage.success("更新成功");
  getCfg();
}

onMounted(() => {
  setTimeout(() => {
    getCfg();
  }, 500);
});
const uploadRef = ref();
const files = ref([]);

async function templateOperate(type) {
  const urlDownload = function (url, name) {
    var a = document.createElement("a");
    // console.log(url)
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  };
  if (type === "export") {
    const res = await licenseRequest();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `${moment().format("YYYYMMDDHHmmss")}`);
    // window.open(url)
  }
  if (type === "download") {
    const res = await downloadTemplate();
    console.info(res);
    const url = URL.createObjectURL(res);
    urlDownload(url, `finger_template_${moment().format("YYYYMMDDHHmmss")}.csv`);
  }
  if (type === "import") {
    const tempInput = document.createElement("input");
    tempInput.type = "file";
    tempInput.accept = ".xls,.xlsx,.csv";
    tempInput.click();
    tempInput.addEventListener("change", async () => {
      const res = await importData({ file: tempInput.files[0] });
      if (res.success) {
        ElMessage.success("导入成功");
        loadDataCb();
      } else {
        ElMessage.warning(res.msg);
      }
    });
  }
  // this.waitOperator();
}
</script>

<template>
  <el-card>
    <template #header>
      <div class="card-header h-box justify-between">
        <span>授权</span>
        <base-button @click="showHandle = true" type="edit_text"></base-button>
      </div>
    </template>
    <div style="height: 140px">
      <el-form
        v-if="updateFormData.isLicence"
        ref="updateFormRef"
        :model="updateFormData"
        :rules="updateFormRules"
        label-width="90px"
        label-suffix="："
      >
        <!--        <div>{{ updateFormData.license?.replaceAll("版本", "") }}有效期:</div>-->
        <div class="mg-t-sm">永久有效</div>
        <!--        <div class="mg-t-sm">{{ updateFormData.requestStart }} ~~ {{ updateFormData.requestEnd }}</div>-->
        <!--        <el-form-item label="版本类型">{{ updateFormData.license }}有效期</el-form-item>-->
        <!--        <el-form-item label="激活时间">{{ updateFormData.request }}</el-form-item>-->
        <!--        <el-form-item label="授权">{{ updateFormData.day }}天</el-form-item>-->
      </el-form>
      <el-empty style="margin: 0px; padding: 0px" :image-size="100" description="暂无授权" v-else></el-empty>
    </div>
  </el-card>
  <base-dialog confirmText="激活" @confirm="submitCb()" width="500px" :title="'激活'" v-model="showHandle">
    <template #header>
      <div class="dialog-header">
        <div class="text-bold">激活</div>
        <div>
          <base-button @click="templateOperate('export')" type="download_code_icon"></base-button>
        </div>
      </div>
    </template>
    <el-form v-loading="loading" class="">
      <el-form-item label="">
        <el-upload
          class="upload-demo"
          v-model:file-list="files"
          :limit="1"
          drag
          style="width: 100%"
          :auto-upload="false"
          ref="uploadRef"
          accept=".dat"
        >
          <div class="h-box">
            <span>请上传授权文件</span>
            <el-icon class="mg-l-sm">
              <Upload />
            </el-icon>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
  </base-dialog>
</template>

<style lang="scss" scoped>
.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 10px;
}
</style>
